package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.activity.HomeworkListActivity.MyAdapter;
import com.ycsj.goldmedalnewconcept.activity.HomeworkListActivity.MyAdapter.ViewHolder;
import com.ycsj.goldmedalnewconcept.bean.HomeworkListResponse;
import com.ycsj.goldmedalnewconcept.bean.HomeworkListResponse.HomeworkListDetail;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;
import com.ycsj.goldmedalnewconcept.R;

//已发布作业
public class HomeworkListActivity extends Activity {

	private ListView lv_homework;
	private ImageView iv_back;
	private String account;
	private String role;
	private String page;
	private TextView tv_empty;
	private TextView loadTextView;
	private TextView tv_rili;
	private View footerView;
	private boolean isLoading = false;
	private int i = 0;
	private int index = 0;
	private String yearmonth;
	private Intent intent;
	private ArrayList<HomeworkListDetail> list = new ArrayList<HomeworkListDetail>();

	TimePickerView pvTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_homeworklist);

		page = "0";
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		intent = getIntent();

		yearmonth = TimeUtil.getYearMonth();

		Log.e("TimeUtil", yearmonth);

		initView();
		setOnListener();
		initData();
	}

	private void initView() {
		lv_homework = (ListView) findViewById(R.id.lv_homework);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
		tv_rili = (TextView) findViewById(R.id.tv_rili);

		footerView = this.getLayoutInflater().inflate(
				R.layout.load_more_homework, null);
		// loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);

		lv_homework.setFriction(ViewConfiguration.getScrollFriction() * 10);

		// 初次进入的时候让标题栏的时间显示为当前的月份
		tv_rili.setText((Calendar.getInstance().get(Calendar.MONTH) + 1) + "");
	}

	private void setOnListener() {

		footerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!isLoading) {
					loadTextView.setText("正在加载...");
					isLoading = true;
					i++;
					page = i + "";
					initData();
				}
			}
		});

		iv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		tv_rili.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pvTime.show();
			}
		});
		// pvTime = new TimePickerView(this,
		// TimePickerView.Type.YEAR_MONTH_DAY);

		// 设置只显示年月
		pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH);

		pvTime.setTime(new Date());

		pvTime.setCyclic(false);

		pvTime.setCancelable(true);
		// 时间选择后回调
		pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

			@Override
			public void onTimeSelect(Date date) {
				page = "0";

				String newYearmonth = getTime(date);

				// 用"-切割"
				String[] datas = newYearmonth.split("-");

				// 分别取出年月
				String year = datas[0];
				String month = datas[1];

				if ("12".equals(month)) {
					// 如果显示的是2016-12月 ,则上传的时间需要时2017-01
					yearmonth = String.valueOf((Integer.valueOf(year) + 1))
							+ "-01";
				} else {
					// 判断month是否以0开头
					if (month.startsWith("0")) {
						// 以0开头,取出第二个字符转化为int 然后+1处理
						int res = Integer.valueOf(month.substring(1)) + 1;

						Log.i("test", "转换后的res的月份值是" + res);
						if (res < 10) {
							yearmonth = year + "-0" + res;
						} else {
							yearmonth = year + "-" + res;
						}

					} else {
						// 不以0开头,10和11
						int res = Integer.valueOf(month) + 1;
						yearmonth = year + "-" + res;
					}
				}

				Log.i("test", "获取到的时间是:" + yearmonth);

				// 重新设置标题栏显示月份的TextView
				tv_rili.setText(yearmonth.split("-")[1]);

				Log.e("time", yearmonth);
				initData();
			}

		});

	}

	/**
	 * 将Date时间转化为年月的方法
	 * 
	 * @param date
	 * @return
	 */
	public String getTime(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		return format.format(date);
	}

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		String Url = Constant.SERVER_URL + "ManageMsg?type=4&c=" + account
				+ "&role=" + role + "&status=" + "0" + "&yearmonth="
				+ yearmonth + "&page=" + page;
		final Request request = new Request.Builder().url(Url).build();
		// new call
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(callBack);
	}

	Handler handler = new Handler();
	Callback callBack = new Callback() {

		private HomeworkListResponse fromJson;

		@Override
		public void onFailure(Request arg0, IOException arg1) {

		}

		@Override
		public void onResponse(Response arg0) throws IOException {
			String json = arg0.body().string();
			Log.e("test", json);
			Gson gson = new Gson();
			if ("0".equals(page)) {
				list.removeAll(list);
			}

			fromJson = gson.fromJson(json, HomeworkListResponse.class);
			if (fromJson != null) {
				if ("-1".equals(fromJson.state)) {

					if (!"0".equals(page)) {
						handler.postDelayed(new Runnable() {

							@Override
							public void run() {
								loadTextView.setText("已经是最后一条了");
								page = "0";
							}
						}, 0);

					} else {
						handler.postDelayed(new Runnable() {

							@Override
							public void run() {
								tv_empty.setVisibility(tv_empty.VISIBLE);
							}
						}, 0);
					}
				}
			}
			if (!("{\"state\":\"-1\"}").equals(json)) {
				if (fromJson.list != null) {

					list.addAll(fromJson.list);
					if (list != null && list.size() == 10) {
						lv_homework.addFooterView(footerView, null, false);
					}
					index = lv_homework.getFirstVisiblePosition() + 1;
					Log.e("test", index + "");
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							tv_empty.setVisibility(tv_empty.GONE);
							lv_homework.setAdapter(new MyAdapter(
									getBaseContext()));

							if (!"0".equals(page)) {
								lv_homework.setSelection(index);
								isLoading = false;
								loadTextView.setText("加载更多");
							}
						}
					}, 0);
				}
			}
		}
	};

	class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater = null;

		private MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.list_homework, null);
				// holder.img = (ImageView)item.findViewById(R.id.img)
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tv_name);
				holder.tv_content = (TextView) convertView
						.findViewById(R.id.tv_content);
				holder.tv_date = (TextView) convertView
						.findViewById(R.id.tv_date);
				convertView.setTag(holder);
				if (position == 0) {
					holder.tv_name.setTextColor(HomeworkListActivity.this
							.getResources().getColor(R.color.titlered));
				}
			} else {
				holder = (ViewHolder) convertView.getTag();
				if (position != 0) {
					holder.tv_name.setTextColor(HomeworkListActivity.this
							.getResources().getColor(R.color.black));
				} else {
					holder.tv_name.setTextColor(HomeworkListActivity.this
							.getResources().getColor(R.color.titlered));
				}
			}

			holder.tv_name.setText("上次作业点评：" + list.get(position).comment);
			holder.tv_content.setText("本次作业内容：" + list.get(position).content);
			holder.tv_date.setText("发布作业时间:" + list.get(position).update_date);
			return convertView;
		}

		class ViewHolder {
			private TextView tv_name;
			private TextView tv_content;
			private TextView tv_date;
		}
	}
}
